package com.smcdd.cdb.dbo.cdb_dbo.service.presenter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.StoreInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.DataManager;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.NetWorkCodeInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.INotLayMenFg;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.AddMenDianActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.CdbListInfoActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.MenDianActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.adapter.YetAdapter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseFragmentActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseFragmentPresenter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainEncry;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainVersion;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.SelectPicPopupWindow;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.SimpleDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 作者：Administrator on 2017/6/20 12:02
 * 邮箱：zhanghuaiha@gmail.com
 */

public class NotLayMenPresenter extends BaseFragmentPresenter<INotLayMenFg> {
    private YetAdapter adapter;
    private MenDianActivity menDianActivity;
    private SelectPicPopupWindow menuWindow;
    private DataManager manager;
    private CompositeSubscription mCompositeSubscription;
    private SimpleDialog selfDialog;
    private String udid;
    private String eid;
    private String versionName;
    private RecyclerView recycler;
    private LinearLayoutManager linearLayoutManager;
    private StoreInfo store;
    private int cont = 1;

    public NotLayMenPresenter(BaseFragmentActivity context) {
        super(context);
    }

    public void loadContacts(){
        manager = new DataManager(mContext);
        mCompositeSubscription = new CompositeSubscription();
        menDianActivity = getView().getMDActivity();
        recycler = getView().getRecycler();
        linearLayoutManager = new LinearLayoutManager(mContext);
        recycler.setLayoutManager(linearLayoutManager);
        udid = App.SP.getString("udid", "");
        eid = App.SP.getString("id", "");
        versionName = ObtainVersion.getVersionName(mContext);
        setAdapter();
        loadData();
    }

    private void setAdapter() {
        if (adapter == null) {
            adapter = new YetAdapter(mContext);
        }
        recycler.setAdapter(adapter);
        adapter.setItemClickListenter((dataBean, position) -> selectImgs(dataBean,position,dataBean.getId()));
    }

    public void unLoadData(){
        if (mCompositeSubscription.hasSubscriptions()){
            mCompositeSubscription.unsubscribe();
        }
    }


    public void loadData() {
        String time = System.currentTimeMillis() + "";
        String encry = ObtainEncry.getStoreInfog("2", time, versionName, NetWorkCodeInfo.STORE, udid, eid, "20", "0", "0");
        getDataInfo(time,"0",encry);

        //加载更多
        recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int lastVisiblePosition = linearLayoutManager.findLastVisibleItemPosition();
                    if (lastVisiblePosition >= linearLayoutManager.getItemCount() - 1) {
                        Log.e("layoutManager", "一定到底部了 准备加载更多");
                        if (store != null) {
                            if (Integer.parseInt(store.getTotal()) < 20) {
                                return;
                            } else {
                                String time = System.currentTimeMillis() + "";
                                String encry = ObtainEncry.getStoreInfog("2", time, versionName, NetWorkCodeInfo.STORE, udid, eid, "20", cont+"", "0");
                                getDataInfo(time,cont+"",encry);
                                cont++;
                            }
                        }
                    }
                }
            }
        });
    }


    private void getDataInfo(String time,String count,String encry){
        mCompositeSubscription.add(manager.getStoreInfo("2",time, versionName, NetWorkCodeInfo.STORE, udid, eid,"20",count,"0",encry)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<StoreInfo>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(StoreInfo storeInfo) {
                        if (cont == 1) {
                            store = storeInfo;
                            List<StoreInfo.DataBean> data = storeInfo.getData();
                            adapter.addData(data);
                        }else {
                            store = storeInfo;
                            List<StoreInfo.DataBean> data = storeInfo.getData();
                            adapter.addLastData(data);
                        }
                    }
                }));
    }


    //删除
    private void delete(String id,int posotion){
        String time = System.currentTimeMillis() + "";
        String encry = ObtainEncry.Delete("2", time, versionName, NetWorkCodeInfo.DELETE, udid, id, eid);
        mCompositeSubscription.add(manager.Delete("2",time,versionName,NetWorkCodeInfo.DELETE,udid,id,eid,encry)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(codeInt ->{
                    if ( codeInt.code == 200) {
                        adapter.deleteItem(posotion);
                        ToastUtil.showToast("删除成功..");
                    }else {
                        ToastUtil.showToast(codeInt.message);
                    }
                }));
    }

    //将店铺设为已铺设
    private void getLaid(String id,int position){
        String time = System.currentTimeMillis() + "";
        String encry = ObtainEncry.Delete("2", time, versionName, NetWorkCodeInfo.DELETE, udid, id, eid);
        mCompositeSubscription.add(manager.getLaid("2",time,versionName,NetWorkCodeInfo.DELETE,udid,id,eid,encry)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(codeInt ->{
                    if ( codeInt.code == 200) {
                        adapter.deleteItem(position);
                        EventBus.getDefault().post("laid");
                        ToastUtil.showToast("设置成功");
                    }else {
                        ToastUtil.showToast(codeInt.message);
                    }
                }));
    }


    private void Dialog(String id,int posotion) {
        selfDialog = new SimpleDialog(menDianActivity);
        selfDialog.setTitle("提示");
        selfDialog.setMessage("是否删除该记录?");
        selfDialog.setYesOnclickListener("确定", () -> {
            ToastUtil.showToast("点击了--确定--按钮");
            delete(id,posotion);
            selfDialog.dismiss();
        });
        selfDialog.setNoOnclickListener("取消", () -> {
            ToastUtil.showToast("点击了--取消--按钮");
            selfDialog.dismiss();
        });
        selfDialog.show();
    }


    /*
        PopupWindow展示
        */
    private void selectImgs(StoreInfo.DataBean dataBean,int position,String id) {

        ((InputMethodManager) menDianActivity.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(menDianActivity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        menuWindow = new SelectPicPopupWindow(menDianActivity) {

            @Override
            public View initView() {
                LayoutInflater inflater = (LayoutInflater) menDianActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View menuview = inflater.inflate(R.layout.item_mendian_popupwindows, null);

                TextView one = (TextView) menuview.findViewById(R.id.yet_item_popupwindows_one);
                TextView two = (TextView) menuview.findViewById(R.id.yet_item_popupwindows_two);
                TextView three = (TextView) menuview.findViewById(R.id.yet_item_popupwindows_three);
                TextView four = (TextView) menuview.findViewById(R.id.yet_item_popupwindows_four);
                TextView end = (TextView) menuview.findViewById(R.id.yet_item_popupwindows_end);

                /**
                 * 取消按钮销毁事件
                 * by黄海杰@2015-1-7
                 */
                end.setOnClickListener(v ->  dismiss());
                //所属设备
                one.setOnClickListener(v -> {
                    Intent intent = new Intent(menDianActivity, CdbListInfoActivity.class);
                    intent.putExtra("sid",id);
                    intent.putExtra("url",dataBean.getImg_url());
                    intent.putExtra("name",dataBean.getName());
                    menDianActivity.jumpToActivity(intent);
                    dismiss();
                });
                //编辑
                two.setOnClickListener(v -> {
                    Intent intent = new Intent(menDianActivity,AddMenDianActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("dataBean",dataBean);
                    intent.putExtras(bundle);
                    menDianActivity.startActivity(intent);
                    dismiss();
                });
                //将店铺设为已铺设
                three.setOnClickListener(v -> {
                    getLaid(id,position);
                    dismiss();
                });
                //删除店铺
                four.setOnClickListener(v -> {
//                    delete(id,position);
                    Dialog(id,position);
                    dismiss();
                });
                return menuview;
            }
        };
        //设置弹窗位置
        menuWindow.showAtLocation(menDianActivity.findViewById(R.id.md), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }
}